import React, {useCallback, useMemo} from "react";
import {Form, Input} from "antd";

function ChangePassword(props) {
	const {form} = props;
	const {getFieldDecorator} = form

	const compareToFirstPassword = (rule, value, callback) => {
		if (value && value !== form.getFieldValue('password')) {
			callback('两次输入的密码不相等!');
		} else {
			callback();
		}
	};


	const formItems = [
		{
			label: '原密码',
			key: 'old_password',
			options: {
				rules: [
					{
						required: true,
						message: '请输入密码！'
					}
				],
				initialValue: ''
			},
			type: <Input.Password/>
		}, {
			label: '新密码',
			key: 'password',
			options: {
				rules: [
					{
						required: true,
						message: '请输入新密码！'
					}
				],
				initialValue: ''
			},
			type: <Input.Password/>
		},
		{
			label: '确认新密码',
			key: 'password_repeat',
			options: {
				rules: [
					{
						required: true,
						message: '请确认新密码！'
					},
					{
						validator: compareToFirstPassword
					}
				],
				initialValue: ''
			},
			type: <Input.Password/>
		},
	]

	const formOperations = useMemo(
		() => {
			return {
				getFormValue: () => {
					let value = props.form.getFieldsValue()
					return value
				},
				validateFields: () => {
					let canPost = false
					props.form.validateFields((errors, values) => {
						console.log(errors);
						if (errors === null) {
							canPost = true
						}
					})
					return canPost
				}
			}
		},
		[props.form],
	)
	props.onRef(formOperations)
	return (
		<Form>
			{
				formItems.map(item => {
					let {label, key, options, type} = item
					return (
						<Form.Item label={label} key={key}>
							{
								getFieldDecorator(key, options)(type)
							}
						</Form.Item>
					)
				})
			}
		</Form>
	)
}

export default Form.create()(ChangePassword);
